import pygame
from game.game import Game
from game.card import Card
from gui.game_window import GameWindow
import os
from game.cards import Strike, DoubleStrike  # 使用新的导入路径

def initialize_starter_deck():
    """初始化起始卡组"""
    return [
        Strike(),
        Strike(),
        DoubleStrike()
    ]

def main():
    # 添加调试信息
    print("Current working directory:", os.getcwd())
    print("Script location:", os.path.dirname(os.path.abspath(__file__)))
    
    try:
        game = Game()
        window = GameWindow()
        clock = pygame.time.Clock()
        
        # 游戏状态
        game_state = "title"  # title, character_select, battle
        
        running = True
        hovered_card = None
        
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if game_state == "title":
                        game_state = "character_select"
                    elif game_state == "character_select":
                        # 处理角色选择
                        mouse_pos = pygame.mouse.get_pos()
                        character_class = handle_character_select(mouse_pos)
                        if character_class:
                            game_state = "battle"
                            window.start_battle_transition()
                            game.start_new_game(character_class)
                            game.player.deck = initialize_starter_deck()
                            game.player.draw_card(5)
                            game.player.sort_hand()
                    elif game_state == "battle":
                        # 处理战斗中的点击
                        handle_battle_click(event.pos, game, window)
                elif event.type == pygame.MOUSEMOTION:
                    if game_state == "battle":
                        hovered_card = window.handle_card_hover(event.pos)
            
            # 更新画面
            if game_state == "title":
                window.draw_title_screen()
            elif game_state == "character_select":
                window.draw_character_select()
            elif game_state == "battle":
                window.draw_battle_screen(game, hovered_card)
            
            pygame.display.flip()
            clock.tick(60)
        
        pygame.quit()
    except Exception as e:
        print(f"Error initializing game: {e}")
        import traceback
        traceback.print_exc()
        return

def handle_battle_click(pos, game, window):
    """处理战斗画面中的点击"""
    # 如果有战利品界面，处理卡牌选择
    if game.current_room["completed"] and game.battle_rewards:
        if game.battle_rewards.get("selected_card") is None:
            # 检查是否点击了奖励卡牌
            card_spacing = 220
            start_x = window.width//2 - card_spacing
            
            for i, card in enumerate(game.battle_rewards["cards"]):
                card_rect = pygame.Rect(
                    start_x + i * card_spacing - 60,
                    260,
                    120,  # 卡牌宽度
                    180   # 卡牌高度
                )
                
                if card_rect.collidepoint(pos):
                    # 选中卡牌
                    game.battle_rewards["selected_card"] = card
                    game.player.deck.append(card)
                    
                    # 播放选择音效和特效
                    window.handle_card_select(card, pos)
                    
                    # 延迟一下再进入下一个房间（给特效播放的时间）
                    pygame.time.wait(300)
                    
                    # 进入下一个房间
                    game.enter_next_room()
                    
                    # 重置玩家状态
                    game.player.stats["current_mana"] = game.player.stats["max_mana"]
                    game.player.stats["block"] = 0
                    game.player.draw_card(5)
                    
                    # 添加提示消息
                    window.ui_manager.add_message(f"获得了新牌：{card.name}！", color=(255, 215, 0))
                    window.ui_manager.add_message("进入新的房间！", color=(255, 255, 0))
                    return
            return  # 如果已经选择了卡牌，不处理其他点击
    
    # 检查是否点击了结束回合按钮
    if window.buttons['end_turn'].collidepoint(pos):
        enemy_action = game.end_turn()
        if enemy_action:
            if enemy_action["type"] in ["attack", "ability"]:
                damage = max(0, enemy_action["damage"] - game.player.get_defense())
                window.ui_manager.add_message(
                    f"{game.current_room['content']['enemy'].name} 使用 {enemy_action.get('name', '攻击')} 造成 {damage} 点伤害",
                    color=(255, 0, 0)
                )
                game.player.stats["current_hp"] -= damage
        window.ui_manager.add_message("新的回合开始！")
        return
    
    # 检查是否点击了手牌
    card_clicked = check_card_click(pos, game.player.hand)
    if card_clicked is not None:
        if game.player.stats["current_mana"] >= card_clicked.cost:
            # 获取目标位置（敌人位置）
            target_pos = (window.width//2, window.height//3)
            
            # 执行游戏逻辑
            action = {"type": "card", "card": card_clicked}
            if game.execute_action(action):
                # 处理卡牌使用效果和动画
                window.handle_card_play(card_clicked, target_pos)
                # 播放音效
                window.sound_manager.play_sound('card_play')
            else:
                window.ui_manager.add_message("法力值不足！", color=(255, 0, 0))

def check_card_click(pos, hand):
    """检查点击位置是否在某张卡牌上"""
    # 计算每张卡牌的位置和大小
    card_width = 120
    card_height = 180
    start_x = (960 - (len(hand) * (card_width + 20))) // 2  # 修正窗口宽度
    card_y = 640 - card_height - 20  # 修正窗口高度
    
    # 从右到左检查，这样最上层的卡牌会优先被选中
    for i in range(len(hand) - 1, -1, -1):
        card = hand[i]
        card_x = start_x + i * (card_width + 20)
        card_rect = pygame.Rect(card_x, card_y, card_width, card_height)
        if card_rect.collidepoint(pos):
            return card
    return None

def handle_character_select(pos):
    """处理角色选择的点击"""
    # 计算角色卡片的位置和大小
    card_width = 200
    card_height = 300
    
    # 战士卡片区域
    warrior_rect = pygame.Rect(
        960//3 - card_width//2,  # x
        640//2 - card_height//2,  # y
        card_width,
        card_height
    )
    
    # 法师卡片区域
    mage_rect = pygame.Rect(
        2*960//3 - card_width//2,  # x
        640//2 - card_height//2,  # y
        card_width,
        card_height
    )
    
    if warrior_rect.collidepoint(pos):
        return "warrior"
    elif mage_rect.collidepoint(pos):
        return "mage"
    return None

if __name__ == "__main__":
    main() 